package ManagedBeans;

import Utilitaires.PropertiesReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Properties;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import org.primefaces.json.JSONException;
import org.primefaces.json.JSONObject;

/**
 *
 * @author Dos Reis Adrien
 */
@ManagedBean
@RequestScoped
public class UsersBean 
{
    private int id;
    private String login;
    private String password;
    private String lastName;
    private String firstName;
    private String mail;
    
    private Properties properties;
    /**
     * Creates a new instance of UsersBean
     */
    public UsersBean()
    {
        this.id = 1;
        properties = PropertiesReader.getProperties();
    }
    
    public void getByLogin() throws MalformedURLException
    {
        URL url = new URL("http://"+properties.getProperty("adress")+":"+properties.getProperty("port")+"/user/l/"+this.login);
    }
    
    public void getById() throws MalformedURLException, IOException
    {
        URL url = new URL("http://"+properties.getProperty("adress")+":"+properties.getProperty("port")+"/user/"+this.id);
        HttpURLConnection connexion = (HttpURLConnection) url.openConnection();
        connexion.setRequestMethod("GET");
        
        try
        {
            String result = ""; 
            String line = "";

            BufferedReader rd = new BufferedReader(new InputStreamReader(connexion.getInputStream()));
            while ((line = rd.readLine()) != null) {
                result += line;
            }
            rd.close();
        
            System.out.println(result);
        }
        finally
        {
            System.out.println(connexion.getResponseCode());
            System.out.println(connexion.getResponseMessage());
        }
    }
    
    // MIse à jour de l'utilisateur courant dans la base
    public void update() throws MalformedURLException, IOException
    {
        URL url = new URL("http://"+properties.getProperty("adress")+":"+properties.getProperty("port")+"/user/"+this.id);
        HttpURLConnection connexion = (HttpURLConnection) url.openConnection();
        connexion.setDoOutput(true);
        connexion.setRequestMethod("POST");
        
        try
        {
            OutputStreamWriter out = new OutputStreamWriter(connexion.getOutputStream());
            String json = this.generateJson();
            out.write(json);
            out.close();
        }
        catch(Exception e)
        {}
        finally
        {
            System.out.println(connexion.getResponseCode());
            System.out.println(connexion.getResponseMessage());
        }
        System.out.println("UsersBean.update()");
    }
    
    // Sauvegarde en base de l'utilisateur
    // On passe au serveur une chaîne JSON contenant toutes les informations de
    // l'utilisateur à créer
    public void save() throws MalformedURLException, IOException
    {
        URL url = new URL("http://"+properties.getProperty("adress")+":"+properties.getProperty("port")+"/user");
        HttpURLConnection connexion = (HttpURLConnection) url.openConnection();
        connexion.setDoOutput(true);
        connexion.setRequestMethod("PUT");
        
        try
        {
            OutputStreamWriter out = new OutputStreamWriter(connexion.getOutputStream());
            String json = this.generateJson();
            out.write(json);
            out.close();
        }
        catch(Exception e)
        {}
        finally
        {
            System.out.println(connexion.getResponseCode());
            System.out.println(connexion.getResponseMessage());
        }
        System.out.println("UsersBean.save()");
    }
    
    // Suppression de l'utilisateur associé au paramètre id
    public void delete() throws MalformedURLException, IOException
    {
        URL url = new URL("http://"+properties.getProperty("adress")+":"+properties.getProperty("port")+"/user/"+this.id);
        HttpURLConnection connexion = (HttpURLConnection) url.openConnection();
        connexion.setDoOutput(true);
        connexion.setRequestProperty(
            "Content-Type", "application/x-www-form-urlencoded" );
        connexion.setRequestMethod("DELETE");
        connexion.connect();
        
        // Si 404 = Utilisateur inconnu
        if (connexion.getResponseCode() == 404)
        {
            FacesMessage message = new FacesMessage("Echec", "Utilisateur introuvable en base.");
            FacesContext.getCurrentInstance().addMessage(null, message);
        }
        
        // Si 400 = Erreur lors de la suppression
        if (connexion.getResponseCode() == 400)
        {
            String failure = ResourceBundle.getBundle("/Langues/Bundle").getString("echec");
            String error = ResourceBundle.getBundle("/Langues/Bundle").getString("erreurSuppression");
            
            FacesMessage message = new FacesMessage(failure, error);
            FacesContext.getCurrentInstance().addMessage(null, message);
        }
        
        System.out.println(connexion.getResponseCode());
        System.out.println(connexion.getResponseMessage());
        
        System.out.println("http://"+properties.getProperty("adress")+":"+properties.getProperty("port")+"/user/"+this.id);
        
        System.out.println("UsersBean.delete()");
    }

    public int getId() {
        return id;
    }

    public void setId(int id) 
    {
        this.id = id;
    }

    public String getLogin() {
        return login;
    }

    public void setLogin(String login) {
        this.login = login;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getMail() {
        return mail;
    }

    public void setMail(String mail) {
        this.mail = mail;
    }
    
    // Génération du JSON associé à l'User courant
    public String generateJson() throws JSONException
    {
        JSONObject json = new JSONObject();
        json.put("login", this.login);
        json.put("password", this.password);
        json.put("firstName", this.firstName);
        json.put("lastName", this.lastName);
        json.put("mail", this.mail);
        
        return json.toString();
    }
}
